package com.example.shop_2302.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.base.mvvm.BaseFragment
import com.example.shop_2302.R
import com.example.shop_2302.adapter.OneAdapter
import com.example.shop_2302.adapter.TwoAdapter
import com.example.shop_2302.databinding.FragmentCategoryBinding


class CategoryFragment : BaseFragment<FragmentCategoryBinding,CategoryViewModel>() {
    lateinit var oneAdapter: OneAdapter
    lateinit var twoAdapter: TwoAdapter

    var flag = false//是否是点击引起的rvTwo的滚动
    override fun initView() {
        oneAdapter = OneAdapter()
        binding.rvOne.adapter = oneAdapter
        binding.rvOne.layoutManager = LinearLayoutManager(context)

        twoAdapter = TwoAdapter()
        binding.rvTwo.adapter = twoAdapter
        val layoutManager = LinearLayoutManager(context)
        binding.rvTwo.layoutManager = layoutManager

        viewModel.category()
        //点击oneAdapter，文字选中状态转移  右侧rv滚动了
        oneAdapter.setOnItemClickListener { adapter, view, position ->
            oneAdapter.setId(oneAdapter.data[position].id)
            //
            flag = true//点击引起rvtwo滚动
            layoutManager.scrollToPositionWithOffset(position,0)
            flag = false//滚动结束，
        }
        //监听rvtwo滚动事件  //如果是点击引起的，不做任何操作   //不是点击事件引起的，判断移动过后显示的默认一个的id 是否和rvone中的选中id 相同 //相同不做任何操作
        //如果不同，将rvone选中的值修改为rvTwo显示的id的值
        binding.rvTwo.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            if(!flag){
                val position = layoutManager.findFirstVisibleItemPosition()//找到第一个可见的item的下标
                if(oneAdapter.selectId!=twoAdapter.data[position].id){
                    oneAdapter.setId(twoAdapter.data[position].id)
                }
            }
        }
    }

    override fun initData() {
        viewModel.cateSuccess.observe(this){
            if(it.code==200){
                oneAdapter.data.clear()
                oneAdapter.data.addAll(it.data)
                oneAdapter.notifyDataSetChanged()


                twoAdapter.data.clear()
                twoAdapter.data.addAll(it.data)
                twoAdapter.notifyDataSetChanged()
            }

        }
    }

    override fun getViewModel(): Class<CategoryViewModel> = CategoryViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_category

}